Ext.onReady(function(){
  var Tree = Ext.tree;
   var selNode = null;
    var tree ;
// shorthand
 var accordion = new Ext.Panel({
                region:'west',
                margins:'5 0 5 5',
                split:true,
                width: 210,
                margins:'0 0 0 0',
                autoScroll:true,
                border:false,
                html:'<div id="leftTree"></div>'
            });
 var accordion02 = new Ext.Panel({
                region:'center',
                margins:'5 0 5 5',
                split:true,
                margins:'0 0 0 0',
                autoScroll:true,
                html:'<div id="CON_R"></div>'
            });

            var viewport = new Ext.Panel({
            	renderTo:'layout-borderlayout-main',
                layout:'border',
                margins:'0 0 0 0',
                autoWidth:true,
                height:600,
                items:[
                    accordion, accordion02]
            });
  	/**
	 * 右键菜单
	 */
  var ctxMenu = new Ext.menu.Menu({
        id:'copyCtxs',
        items: [{
                id:'orgadd',
                handler:sortAdd,
                cls:'expand-all',
                text:'增加'
            },{
                id:'orgmodi',
                handler:sortModi,
                cls:'collapse-all',
                text:'修改'
            },{
                id:'sortImple',
                handler:sortImple,
                cls:'collapse-all',
                text:'Excel导入'
            }
            ,{
                id:'orgdel',
                handler:sortdel,
                cls:'collapse-all',
                text:'删除'
            }]
    });
       var win;
     /***添加分类**/
    function sortAdd(){
       if(selNode == null)
       	return;
       	 Ext.MessageBox.prompt('添加分类', '请输入分类名称:', addShowResultText);
    }
    function addShowResultText(x,text){
    	if(x=='ok')
    		sortAjax("/pre/sortAc.do",{id:selNode.id,sortDis:'addSort',sortName:text},addSu,sortFail);
    }
    function sortImple()
    {
    if(selNode == null)
     	return;
     var form = new Ext.form.FormPanel({   
     labelAlign: 'right',   
     labelWidth: 60,
     url: '/pre/sortAc.do?sortDis=excelImpleSort&pdi='+selNode.id,//fileUploadServlet   
     fileUpload: true,
     items: [{
        xtype: 'textfield',   
        fieldLabel: '文件名',   
        name: 'file', 
        inputType: 'file'//文件类型   
        
      },new Ext.form.Label({
      html:'<font color="red">Excel导入说明:<br>⑴文件必须为Excel;&nbsp;&nbsp;⑵导入格式为缩进形式-(<a target="_blank" href="examples.xls">例</a>);&nbsp;&nbsp;⑶解析方式:至上而下执行,数据列位置可以随意,但上下级缩进等差等于1,如果相邻两数据等差大于1就继续往上找,没有就作为根节点;&nbsp;&nbsp;⑷选择的分类节点及为导入数据的父节点;<font>'
      })]      
  	});  

	    var AddEmpWin = new Ext.Window({
			title: '分类导入',
			layout:'fit',
			width:300,
			height:200,
			plain: true,
			items:form,
		    buttons: [{   
		        text: '上传',   
		        handler: function() {   
		        form.getForm().submit({
		        waitMsg: '正在提交数据，请等待...',  
		        success: function(form, action){   
		           Ext.Msg.alert('信息', '文件上传成功！');  
		            tree.root.reload();
		           AddEmpWin.hide();  
		        },   
		       failure: function(){   
		          Ext.Msg.alert('错误', '文件上传失败');   
		       }   
		     });   
		    }   
		  },
		  {
			text: '取消',
			handler: function(){
				AddEmpWin.hide();
			}
		  } 
			]
		});
		AddEmpWin.show(this);
    }
    

     function modiShowResultText(x,text){
      if(text !=selNode.text)
    	{
    	selNode.setText(text);
    	sortAjax("/pre/sortAc.do",{id:selNode.id,sortDis:'editSort',sortName:text},addSu,sortFail);
    	
    	}
    }
    function delShowResultText(a,b){
     if(a=='yes')
     {
      root.removeChild(selNode);
      sortAjax("/pre/sortAc.do",{id:selNode.id,sortDis:'delSort'},function(){},sortFail);
      }
    }

    function addSu(request){
	    var obj = eval("["+request.responseText+"]");
	    if(obj[0].success)
	     {
	       fcm(obj[0].data[0].sortId,obj[0].data[0].sortName);
	     }
	     else alert("添加失败!");
    }
    function sortFail(){alert("操作失败!");}
    function sortModi(node){  
    if(selNode == null)
       	return;
       	 Ext.MessageBox.prompt('添加分类', '请输入分类名称:', modiShowResultText,null,null,selNode.text);
    }

    function sortdel()
    {
      if(selNode == null)
       	return;
       Ext.MessageBox.confirm('确认', '请确认是否删除,删除后不可恢复!', delShowResultText);
    
     }
    
      tree = new Tree.TreePanel({
        el:'leftTree',
		autoScroll:true,
		root:root,
		animate:true,
		enableDD:true,
		autoHeight :true,
		border:false,
		rootVisible:true,
		allowDrag:true,
		containerScroll: true,
        loader: new Tree.TreeLoader({
            dataUrl:'/pre/sortAc.do',
            baseParams:{id:1,sortDis:'list'}
        })
    });

	tree.on("beforeload", function(treeLoader, node) {
	 	tree.loader.baseParams.id = treeLoader.id;
    }, this);
    /***把刚加上的子节点 属性 是否是节点设置成 false,不然不接受拖拽添加***/
    tree.on('append',function(tree,parent,node,index ){
    	node.leaf = false;
    });
   tree.on('beforemovenode',function(mytree,curNode, oldParent, newParent, index){
    	sortAjax("/pre/sortAc.do",{sortId:curNode.id,parentSortId:newParent.id,sortDis:'updateSort'},function(){},sortFail);  
    });
  
  
    // set the root node
    var root = new Tree.AsyncTreeNode({
        text: '分类',
        draggable:false,
        expandable: true,
        id:'0'
    });
    tree.setRootNode(root);

    // render the tree
    tree.render();
    root.expand();
    tree.on('contextmenu',prepareCtx);
   
     tree.on('click', function(node){
	     if(!node.hasChildNodes())
	     {
	     // accordion02.load('/pre/perInfo.do?perInfo=list&id='+node.id);
	     var url ='/pre/perInfo.do?perInfo=list&sortId='+node.id;
	     accordion02.getEl().dom.lastChild.lastChild.innerHTML='<iframe scrolling="auto" frameborder="0" width="100%" height="100%" src="'+url+'"></iframe>';
	      }
	       else{node.unselect();};
	});

   function prepareCtx(node, e){
        selNode = node;
        node.select();
	    ctxMenu.showAt(e.getXY());
    }

	function fcm(id,cname){
		if(selNode != null){
	    	var m1 = new Ext.tree.TreeNode({
	        text: cname,
	        draggable:true,
	        id:id
	    	});
	    	selNode.leaf=false;
	    	selNode.appendChild(m1);
		}
	}
});


function sortAjax(url,params,sucFn,faiFn){
	Ext.Ajax.request({
	   url: url,
	   success: sucFn,
	   failure: faiFn,
	   params: params
	});
}
